﻿using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Services;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Yitter.IdGenerator;

namespace CoreShop.App
{
    public partial class frmFoodpackOptional : UIForm
    {
        private List<corecmsfoodordering> packdetailList = null;
        private List<corecmsfoodpack> packList = null;
        public corecmsfoodordering orderingParent;

        public frmFoodpackOptional()
        {
            InitializeComponent();
        }

        private void frmfoodpack_Load(object sender, EventArgs e)
        {
            lblFoodName.Text = "套菜名称：" + orderingParent.name;
            packList = new corecmsfoodpackServices().GetListByFoodId(orderingParent.foodId);
            packdetailList = new corecmsfoodorderingServices().GetListByFoodPackId(orderingParent);
            if (packdetailList.Count == 0)
            {
                ShowInfoTip("没有套菜明细,无法选择。");
                btnOk.Visible = false;
                return;
            }
            BindFoodList();
        }

        private void BindFoodList()
        {
            layFoodList.Visible = false;
            layFoodList.Clear();
            string packGroupName = "";
            btnOk.Enabled = false;
            foreach (var item in packList)
            {
                string sSelectType = EnumHelper.GetDescByValue<GlobalEnumVars.FoodPackSelectType>(item.selectType);
                string packName = item.name;
                if (string.IsNullOrEmpty(packName)) packName = item.id.ToString();

                packGroupName = string.Format("{0} ---(说明:{1},选择{2}~{3}项)", packName, sSelectType, item.quantityStar, item.quantityEnd);
                if (string.IsNullOrEmpty(packGroupName)) packGroupName = item.id.ToString();
                AddType(packGroupName);
                var packGroup = packdetailList.Where(p => p.packGroupId == item.id).ToList();
                if (item.selectType == 2)
                    packGroup.ForEach(p => p.itemCount = 1);
                int rows = CommFunc.ConvertToInt32(Math.Ceiling(packGroup.Count / 5.0));
                AddItems(packGroupName, packGroup,item);
            }
            layFoodList.Visible = true;
        }

        public void AddType(string type)
        {
            UIMenuItemSeparator item = new UIMenuItemSeparator(type, 40);
            item.SetOtherMode();
            item.Width = layFoodList.Width - 30;
            layFoodList.Add(item);
        }


        public void AddItems(string packTypeName, List<corecmsfoodordering> items, corecmsfoodpack packItem)
        {
            foreach (var item in items)
            {
                string price = string.Format("￥{0}", item.price.ToString("0.##"));
                var info = new UAddFoodItemInfo(packTypeName, item.name, price, item.itemCount, item.rowId.ToString());
                if (packItem.isSelectSame)
                    info.MaxCount = packItem.quantityEnd;
                else info.MaxCount = 1;
                AddFoods(info);
            }
        }

        public void AddFoods(UAddFoodItemInfo info)
        {
            UIAddFoodsItem item = new UIAddFoodsItem();
            item.Tag = info.ItemId;
            item.Type = info.Type;
            item.Food = info.Food;
            item.Money = info.Money;
            item.Count = info.Count;
            item.MaxCount = info.MaxCount;
            item.OnValueChanged += FoodsItem_OnValueChanged;
            item.OnAddValueError += FoodsItem_OnAddValueError;
            layFoodList.Add(item);
        }

        private void FoodsItem_OnValueChanged(object sender, System.EventArgs e)
        {
            UIAddFoodsItem info = (UIAddFoodsItem)sender;
            int number = info.Count;
            int rowId = CommFunc.ConvertToInt32(info.Tag);
            var packdetail = packdetailList.Find(p => p.rowId == rowId);
            if (packdetail == null)
            {
                UIMessageBox.Show("选择失败，选择的明细未能找到。", "系统出错:", UIStyle.Orange, UIMessageBoxButtons.OK);
                return;
            }
            int addNumber = number - packdetail.itemCount;
            long packGroupId = packdetail.packGroupId;
            var itemSum = packdetailList.Where(p => p.packGroupId == packGroupId).Sum(p => p.itemCount) + addNumber;
            if (itemSum > packdetail.packGroupQuantity)
            {
                info.Count = packdetail.itemCount;
                string msg = string.Format("本组选择的数量不能超过{0}", packdetail.packGroupQuantity);
                ShowErrorTip(msg);
                return;
            }
            packdetail.itemCount = number;
            if (packdetailList.Sum(p => p.itemCount) == packList.Sum(p => p.quantityEnd))
                btnOk.Enabled = true;
            else btnOk.Enabled = false;
        }

        private void FoodsItem_OnAddValueError(object sender, System.EventArgs e)
        {
            UIAddFoodsItem info = (UIAddFoodsItem)sender;
            int maxNumber = info.MaxCount;
            string msg = string.Format("选择的数量不能超过{0}", maxNumber);
            ShowErrorTip(msg);
        }

        private void btnCancel_Click(object sender, System.EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            //数量归零，重新计算
            foreach (var item in packdetailList)
            {
                item.itemCount = 0;
            }

            List<corecmsfoodordering> packdetail_save = new List<corecmsfoodordering>();
            List<UAddFoodItemInfo> infos = new List<UAddFoodItemInfo>();
            foreach (var ctrl in this.GetControls<UIAddFoodsItem>(true))
            {
                int id = CommFunc.ConvertToInt32(ctrl.Tag);
                int count = ctrl.Count;
                var packdetail = packdetailList.Find(p => p.rowId == id);
                packdetail.itemCount = count;
            }
            string strMsg = "";
            foreach (var pack in packList)
            {
                string packName = pack.name;
                var itemSum = packdetailList.Where(p => p.packGroupId == pack.id).Sum(p => p.itemCount);
                if (itemSum > pack.quantityEnd)
                {
                    string msg = string.Format("<{0}>选择的数量不能超过{0}", pack.quantityEnd);
                    UIMessageBox.Show(msg, "选择:", UIStyle.Orange, UIMessageBoxButtons.OK);
                    return;
                }
                if (itemSum < pack.quantityStar)
                {
                    if (!string.IsNullOrEmpty(strMsg)) strMsg = strMsg + ";";
                    strMsg = strMsg + string.Format("<{0}>选择的数量小于{0}", pack.quantityEnd);
                }
            }
            if (!string.IsNullOrEmpty(strMsg))
                if (!ShowAskDialog(strMsg)) return;

            orderingParent.sourceId = (long)YitIdHelper.NextId();
            var foodorderingList = new List<corecmsfoodordering> { orderingParent };
            int rowId = orderingParent.rowId;
            foreach (var item in packdetailList)
            {
                if (item.itemCount > 0)
                {
                    rowId++;
                    item.orderId = orderingParent.orderId;
                    item.sourceId = orderingParent.sourceId;
                    item.billerId = AppConstVars.sysUser.id;
                    item.rowId = rowId;
                    item.quantity = item.itemCount * item.foodPackQuantity;
                    item.foodPackQuantity = item.quantity;
                    foodorderingList.Add(item);
                }
            }

            var bl = new corecmsfoodorderingServices().InsertRange(foodorderingList);
            if (!bl)
            {
                UIMessageBox.Show("保存失败。", "系统出错-SaveOrderingFeed:", UIStyle.Orange, UIMessageBoxButtons.OK);
                return;
            }
            this.DialogResult = System.Windows.Forms.DialogResult.OK;

        }
    }
}
